package com.hyk.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.hyk.domain.SysMenu;
import com.hyk.domain.SysRole;
import com.hyk.feign.JwtToken;
import com.hyk.feign.OAuth2FeignClient;
import com.hyk.model.UserLoginModel;
import com.hyk.service.SysMenuService;
import com.hyk.service.SysRoleService;
import com.hyk.service.SysUserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysUserLoginServiceImpl implements SysUserLoginService {

    @Resource
    private OAuth2FeignClient oAuth2FeignClient;

    @Resource
    private SysMenuService sysMenuService;

    @Resource
    private SysRoleService sysRoleService;

    @Value("${basic.token:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basicToken;


    @Override
    public UserLoginModel login(String username, String password) {

        //参数校验
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            throw new RuntimeException("用户名或密码为空");
        }

        //获取token
        ResponseEntity<JwtToken> token = oAuth2FeignClient.getToken("password", username, password, "admin_type", basicToken);
        if(token.getStatusCode() != HttpStatus.OK){
            throw new ApiException(ApiErrorCode.FAILED);
        }
        JwtToken jwtToken = token.getBody();
        String accessToken = jwtToken.getAccessToken();

        //查询菜单数据
        Jwt jwt = JwtHelper.decode(accessToken);
        String jwtJsonStr = jwt.getClaims();
        JSONObject jwtJson = JSON.parseObject(jwtJsonStr);
        Long userId = Long.parseLong(jwtJson.getString("user_name"));
        //直接查询并返回所有菜单
        List<SysMenu> menus = new ArrayList<>();
        boolean flag = false;
        //查询角色
        List<SysRole> sysRoles = sysRoleService.findUserRole(userId);
        for (SysRole sysRole: sysRoles) {
            if(sysRole.getCode().equalsIgnoreCase("ROLE_ADMIN")){
                menus = sysMenuService.list();
                flag = true;
                break;
            }
        }
        if (!flag){
            menus = sysMenuService.findUserMenu(userId);
        }

        //权限数据
        JSONArray authorities = jwtJson.getJSONArray("authorities");
        List<SimpleGrantedAuthority> authorityList = authorities.stream().
                map(authorityJson -> new SimpleGrantedAuthority(
                        authorityJson.toString()))
                .collect(Collectors.toList());


        UserLoginModel userLoginModel = new UserLoginModel();
        userLoginModel.setToken(jwtToken.getTokenType()+ " "+accessToken);
        userLoginModel.setMenus(menus);
        userLoginModel.setAuthorities(authorityList);

        // TODO: 2021/4/21 存储redis

        return userLoginModel;
    }
}
